﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Xml.Linq;

namespace EzDesk.Utility
{
    public class XmlHelper
    {
        public static string TranslateXml(string xsltUri, string xmlData,params KeyValuePair<string, string>[] keyValues)
        {
            XslCompiledTransform xslTransform = new XslCompiledTransform();
            xslTransform.Load(xsltUri);

            return TranslateXml(xslTransform, xmlData,keyValues);
            
        }

        /// @refactoring
        /// <summary>
        /// 
        /// </summary>
        /// <param name="xslTransform"></param>
        /// <param name="xmlUrl"></param>
        /// <param name="namespaceUri"></param>
        /// <param name="keyValues"></param>
        /// <returns></returns>
        public static string TranslateXml(XslCompiledTransform xslTransform, string xmlData, params KeyValuePair<string, string>[] keyValues)
        {
            XsltArgumentList argumentList = new XsltArgumentList();
            keyValues = keyValues ?? new KeyValuePair<string, string>[] { };
            foreach (var pair in keyValues)
            {
                argumentList.AddParam(pair.Key, string.Empty, pair.Value);
            }

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            XmlReader xr = XmlReader.Create(new StringReader(xmlData));

            xslTransform.Transform(xr, argumentList, XmlWriter.Create(sw, new XmlWriterSettings{ OmitXmlDeclaration= true, ConformanceLevel = ConformanceLevel.Auto}));
            return sb.ToString();
        }
    }
}
